package com.j.lemon.learn.thread.produc1consum;

/**
 * @Author lijunjun
 * @Date 2019-04-22 15:33
 * @Description  synchronized + wait 和 notify 实现的传统的生产者消费者模式  ，两个线程交替对一个资源类进行加减，资源类方法自身控制逻辑
 */
public class TraditionalDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(()->{
            while(true){
                try {
                    shareData.add();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"t1").start();


        new Thread(()->{
            while(true){
                try {
                    shareData.delete();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t1").start();
    }
}

class ShareData{
    int num = 0;

    public void add() throws InterruptedException {
        synchronized(this){
            this.notify();
            System.out.println(Thread.currentThread().getName()+"+1");
            num++;
            this.wait();
        }
    }

    public void delete() throws InterruptedException {
        synchronized (this){
            this.notify();
            System.out.println(Thread.currentThread().getName()+"-1");
            num--;
            this.wait();
        }
    }

}

